package com.magtonic.wuii;

import com.magtonic.communication.BTSerial;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.*;
import android.util.Log;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class WUiiService extends Service {
	final static boolean DEBUG = true;
	final static String TAG = "WUiiService";
	//
	final static String ACTION_WUII_START = "com.magtonic.wuii.action.start"; 
	final static String ACTION_WUII_BT_DISCOVER = "com.magtonic.wuii.action.btdiscover"; 
	final static String ACTION_WUII_BT_CONNECT = "com.magtonic.wuii.action.btconnect"; 
	final static String ACTION_WUII_BT_TX = "com.magtonic.wuii.action.bttx"; 
	final static String ACTION_WUII_BT_RX = "com.magtonic.wuii.action.btrx"; 
	IntentFilter intentWuiiFilter = new IntentFilter();
	final BroadcastReceiver wuiiBrocastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent){
			onReceive_wuiiBrocastReceiver(context, intent);
		}
	};
	//
	BTSerial btSerial;
	String mBtConnectedDeviceName = "";
	private final Handler mCallBackHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			onCallBack_BTMessage(msg);
		}
	};
	
	private final IWUiiService.Stub wuiiBinder = new IWUiiService.Stub() {
        public boolean test(){
        	return this.test();
        }
    };
	//
	public WUiiService() {
		// TODO Auto-generated constructor stub
	}

	//Bind for Service Connection
	class WUiiBinder extends Binder {	
		WUiiService getService() {
			return WUiiService.this;
		}	
	}
	
	@Override
	public void onCreate() {
		if(DEBUG) Log.d(TAG, "onCreate");
		super.onCreate();
		
		//broadcast
		intentWuiiFilter.addAction(ACTION_WUII_START);
		intentWuiiFilter.addAction(ACTION_WUII_BT_DISCOVER);
		intentWuiiFilter.addAction(ACTION_WUII_BT_CONNECT);
		intentWuiiFilter.addAction(ACTION_WUII_BT_TX);
		intentWuiiFilter.addAction(ACTION_WUII_BT_RX);
		this.registerReceiver(wuiiBrocastReceiver, intentWuiiFilter);
	}

	@Override
	public void onDestroy() {
		if(DEBUG) Log.d(TAG, "onDestroy");
		//
		if (btSerial != null)  btSerial.stop();
		//
		this.unregisterReceiver(wuiiBrocastReceiver);
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		if(DEBUG) Log.d(TAG, "onStart");
		super.onStart(intent, startId);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		if(DEBUG) Log.d(TAG, "onBind");
		//return new WUiiBinder();
		return wuiiBinder;
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		if(DEBUG) Log.d(TAG, "onUnbind");
		return super.onUnbind(intent);
	}

	boolean bTest;
	public boolean test(){
		if(bTest) bTest = false;
		else bTest = true;
		
		return bTest;
	}
	//
	private void onReceive_wuiiBrocastReceiver(Context context,	Intent intent) {
		if(DEBUG) Log.d(TAG, "onReceive_wuiiBrocastReceiver " + intent.getAction());
		//
		if(intent.getAction().equals(ACTION_WUII_START)){
			
		}
		else if(intent.getAction().equals(ACTION_WUII_BT_DISCOVER)){
			Intent btConnectIntent = new Intent(getBaseContext(), DeviceListActivity.class);
			btConnectIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			getApplication().startActivity(btConnectIntent);			
		}
		else if(intent.getAction().equals(ACTION_WUII_BT_CONNECT)){
			btSerial = new BTSerial(mCallBackHandler);
			
			if (btSerial != null) {
	            // Only if the state is STATE_NONE, do we know that we haven't started already
	            if (btSerial.getState() == BTSerial.STATE_NONE) {
	            	// Start the Bluetooth services
	            	//btSerial.start();
	            	btSerial.connect(intent.getExtras().getString(BTSerial.DEVICE_ADDR));
	            }
	        }
		}
		else if(intent.getAction().equals(ACTION_WUII_BT_TX)){
			btSerial.write(intent.getByteArrayExtra(BTSerial.DEVICE_TX));
		}
		else if(intent.getAction().equals(ACTION_WUII_BT_RX)){
			
		}
	}

	private void onCallBack_BTMessage(Message msg) {
	  	if(DEBUG) Log.d(TAG, "onCallBack_BTHandler" + msg.what);
    	//
    	switch (msg.what) {
	        case BTSerial.MESSAGE_STATE_CHANGE:
	            if(DEBUG) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
	            //
	            switch (msg.arg1) {
	            	case BTSerial.STATE_NONE:
	            	case BTSerial.STATE_LISTEN:
		                //setStatus(R.string.title_not_connected);
		                break;
		            case BTSerial.STATE_CONNECTING:
		                //setStatus(R.string.title_connecting);
		                break;
		            case BTSerial.STATE_CONNECTED:
		                //setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
		                //mConversationArrayAdapter.clear();
		                break;
    
	            }
	            break;
	        case BTSerial.MESSAGE_WRITE:
	            byte[] writeBuf = (byte[]) msg.obj;
	            // construct a string from the buffer
	            String writeMessage = new String(writeBuf);
	            //mConversationArrayAdapter.add("Me:  " + writeMessage);
	            break;
	        case BTSerial.MESSAGE_READ:
	            byte[] readBuf = (byte[]) msg.obj;
	            // construct a string from the valid bytes in the buffer
	            String readMessage = new String(readBuf, 0, msg.arg1);
	            //mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
	            break;
	        case BTSerial.MESSAGE_DEVICE_NAME:
	            // save the connected device's name
	        	mBtConnectedDeviceName = msg.getData().getString(BTSerial.DEVICE_NAME);
	            Toast.makeText(getApplicationContext(), "Connected to "
	                           + mBtConnectedDeviceName, Toast.LENGTH_SHORT).show();
	            break;
	        case BTSerial.MESSAGE_TOAST:
	            Toast.makeText(getApplicationContext(), msg.getData().getString(BTSerial.TOAST),
	                           Toast.LENGTH_SHORT).show();
	            break;
        }
	}
}
